#pragma once 
#include <iostream>
#include <string>
#include <functional>
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <cstring>
#include <pthread.h>
#include <sys/types.h>
#include <sys/wait.h>
#include"InetAddr.hpp"
#include"Log.hpp"
const static int defaultsockfd = -1;
const static int gbacklog = 16;


enum{
    SOCKET_ERROR = 1,
    BIND_ERROR,
    LISTEN_ERROR,
    USAGE_ERROR
};
class TcpServer;

class ThreadDate{
    public:
        ThreadDate(int fd, InetAddr addr,TcpServer* s)
        :sockfd(fd)
        ,clientaddr(addr)
        ,self(s)
        {}
    public:
        int sockfd;
        InetAddr clientaddr;
        TcpServer* self;
};
// using task_t = std::function<void()>; //线程池
class TcpServer{
    private:
        uint16_t _port; //端口号
        int _listensock;//监听套接字
        bool _isrunning;//
    public:
        TcpServer(int port)
        :_port(port)
        ,_listensock(defaultsockfd)
        ,_isrunning(false)
        {
        }
        void InitServer()
        {
            //1. 创建流式套接字
            _listensock = ::socket(AF_INET,SOCK_STREAM,0);
            if(_listensock < 0)
            {
                LOG(FATAL, "socket error");
                exit(SOCKET_ERROR);
            }
            //2. bind
            struct sockaddr_in local;
            memset(&local,0, sizeof(local));
            local.sin_addr.s_addr = INADDR_ANY;
            local.sin_family = AF_INET;
            local.sin_port = htons(_port);
            int n = ::bind(_listensock, (struct sockaddr*)&local, sizeof(local));
            if(n < 0)
            {
                LOG(FATAL, "bind error");
                exit(BIND_ERROR);
            }
            LOG(DEBUG, "bind success, sockfd is : %d\n", _listensock);
            // 3. tcp是面向连接的，所以通信之前，必须先建立连接。服务器是被连接的
            // tcpserver 启动，未来首先要一直等待客户的连接到来
            n = ::listen(_listensock,gbacklog);
            if(n < 0)
            {
                LOG(FATAL, "listen error");
                exit(LISTEN_ERROR);
            }
            LOG(DEBUG, "listen success, sockfd is : %d\n", _listensock);
        }
        void Service(int sockfd , InetAddr client)
        {
            LOG(INFO,"get a new link, info : %s : %d , fd : %d \n",client.Ip().c_str(), client.Port(),sockfd);
            std::string clientaddr =  "[" +  client.Ip() + ":" + std::to_string(client.Port()) + "]#";
            while(true)
            {
                char buffer[1024];
                size_t n = read(sockfd,buffer,sizeof(buffer) - 1);
                if(n > 0)
                {
                    buffer[n] = 0;
                    std::cout<<clientaddr << buffer << std::endl;
                    std::string echo_string  = "[server echo]#";
                    echo_string += buffer;
                    write(sockfd, echo_string.c_str(), echo_string.size());
                }
                else if(n == 0)
                {
                    //client 退出 && 关闭了连接
                    LOG(INFO,"%s quit\n", clientaddr.c_str());
                    break;
                }
                else{
                    LOG(ERROR, "read error\n",clientaddr.c_str());
                    break;
                }
                // sleep(5);
                // break;
            }
            std::cout<<"server 开始退出" <<std::endl;
            shutdown(sockfd, SHUT_RD);
            std::cout<<"shut _ rd "<< std::endl;
            sleep(10);
        }

        static void* HandlerSock(void * args)
        {
            pthread_detach(pthread_self());
            ThreadDate*td = static_cast<ThreadDate*>(args);
            td->self->Service(td->sockfd, td->clientaddr);
            delete td;
            return nullptr;
        }   
        void Loop()
        {
            _isrunning = true;
            while(_isrunning)
            {
                struct sockaddr_in peer;
                socklen_t len = sizeof(peer);
                int sockfd = ::accept(_listensock, (struct sockaddr* )&peer,&len);
                if(sockfd < 0)
                {
                    LOG(INFO,"accept error");
                    continue;
                }   
                //采用多线程
                pthread_t t;
                ThreadDate *td = new ThreadDate(sockfd, InetAddr(peer), this);
                pthread_create(&t,nullptr, HandlerSock,td);
            }
        }
        ~TcpServer()
        {
            if(_listensock > defaultsockfd)
            {
                ::close(_listensock);
            }
        }
};
